package netty.lifeCycle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;

/**
 * Instruction：
 * Author：@author MaLi
 */
public class InBoundHandlerLifeCycle {
    @Test
    public void testInBoundHandlerLifeCycle() {

        InBoundHandler inBoundHandler = new InBoundHandler();
        //ChannelInitializer的本质: 一个入站Handler, 用于设置PipeLine的
        ChannelInitializer<EmbeddedChannel> channelInitializer = new ChannelInitializer<>() {

            @Override
            protected void initChannel(EmbeddedChannel ch) throws Exception {
                ch.pipeline().addLast(inBoundHandler);
            }
        };
        EmbeddedChannel embeddedChannel = new EmbeddedChannel(channelInitializer);
        embeddedChannel.writeInbound("a");
        embeddedChannel.flush();
        embeddedChannel.writeInbound("b");
        embeddedChannel.flush();

    }

    public static class InBoundHandler extends ChannelInboundHandlerAdapter{
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            super.handlerAdded(ctx);
            System.out.println("0, 当前Handler被添加到PipeLine");
        }

        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            super.channelRegistered(ctx);
            System.out.println("1, 通道注册 - 当前通道绑定到了EventLoop上");
        }

        @Override
        public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
            super.channelUnregistered(ctx);
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            super.channelActive(ctx);
            System.out.println("2, 通道激活 - 所有的Handler完成业务处理器完成了添加");
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            super.channelInactive(ctx);
        }

        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            super.handlerRemoved(ctx);
            System.out.println("Handler被移除");
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            super.channelRead(ctx, msg);
            System.out.println("3, 读取入站数据开始");
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            super.channelReadComplete(ctx);
            System.out.println("4, 读取入站数据完成");
        }

    }
}
